// newHousePackage/pages/newHouseDetail/newHouseDetail.js
import {
  queryNewHouseComment,
  approveComment,
  createComment,
  deleteComment,


} from "../../../service/house_service"
import moment from "./../../../tools/moment"

import { loginWxAction } from "../../../service/config"
import { attentionAction } from "../../../service/attention_service"

import { bindUserRelation } from "../../../service/user_service"

import debounce from "../../../tools/debounce"
import { MAP_KEY } from "../../../service/base_service"
import { mallAddCartRequest } from "../../../service/onetoone_service"

import {
  queryProductDetail,
  querySeckillProductDetail,
  queryProductReplyInfo,
} from "../../../service/jb_product_service"
import {

  queryProductCoupon,
  receiveCoupon
} from "../../../service/jb_coupon_service"
import {
  queryCartCount
} from "../../../service/jb_shopcar_service"
import {
  addCollect,
  cancelCollect,
  queryShareQrCode
} from "../../../service/jb_common_service"
import {
  queryUserInfo
} from "../../../service/jb_mine_service"
import {
  BIND_USER_ID,
  SERVICE_URL,
  SERVICE_ID,
  VIDEO_COVER,
} from "../../../service/base_service"
import mathUtil from "../../../tools/mathUtils/mathUtil"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 详情数据:
    bidProductData: null, //总的商品数据
    productDetail: null,// 具体商品详情
    productAttr: [], //这个是具体的商品规格列表
    productValue: {}, // 这个是当前的商品规格
    productSku: {},//当前商品选中的规格
    couponType: 1,//1,2,3
    themeStyle: "",
    showSharePop: false,
    showCouponPop: false,
    isLogin: false,
    keyBoardHeight: 0,
    showEmptySharePop: false,//没有共享组的情况，创建共享组
    swiperAutoplay: true,
    swiperInterval: 3500,
    swiperDuration: 500,
    singleFormatShowText: "暂无",//单独的户型显示字段
    currentSwiperIndex: 0,//当前swiper下标
    isShowCommentPop: false,//评论弹窗
    //地图key -- 地图相关
    mapSubkey: MAP_KEY,
    latitude: 30.690885,
    longitude: 104.078367,
    enable3d: false,
    showCompass: false,
    enableOverlooking: false,
    enableZoom: false,
    enableScroll: false,
    enableRotate: false,
    drawPolygon: false,
    enableSatellite: false,
    enableTraffic: false,
    maxCommission: 0,//最大佣金
    showCommission: false,
    markers: [{
      id: 0,
      iconPath: "../../img/dingwei.png",
      latitude: 30.690885,
      longitude: 104.078367,
      width: 24,
      height: 24,
      callout: {

      }
    }],
    tempCommissionList: [
      { type: 1 }, { type: 1 }
    ],
    storeInfo: "",//商品简介
    nearestSubWayText: "",//最近地铁信息
    showRulePopup: false,
    showPopupTitle: "推荐规则",
    showRuleContent: "",
    scanExpert: {},//是否有扫描的经纪人
    scrollRefreshStatus: true,
    changePriceTitle: "变价提醒",
    changeOpenTimeTitle: "售卖提醒",
    //吸顶参数
    scrollTop: 0,
    offsetTop: 0,
    toView: "",
    //吸顶参数
    //顶部信息骨架屏配置
    topRowWidths: [
      "60%", "100%"
    ],

    topBanners: [

    ],
    countTimestamp: 0,

    ratingValue: 4,//评论评星
    loadingStatus: false,//数据加载状态
    horizontalModules: [
      { title: "户型", isShow: true }, { title: "资料", isShow: true }, { title: "佣金", isShow: true }, { title: "配套", isShow: true },
      { title: "总平", isShow: true }, { title: "专家", isShow: true }, { title: "动态", isShow: true }, { title: "评论", isShow: true },
    ],
    horizontalSwiperIndex: 100,//默认户型
    houseTypeChangeArr: [

    ],//户型切换数组
    houseTypeList: [

    ],
    houseTypeChangeIndex: 0,//户型默认第一个

    attachFiles: [],//项目资料
    settingRoleRelation: [],//佣金列表
    commentList: [

    ],
    //动态列表
    houseDynamicList: [

    ],

    isShowQrcodeEnter: true,
    expertArr: [

    ],
    tempHouseTimeAxiss: [
      { type: 1, status: 0 }, { type: 1, status: 1 }, { type: 1, status: 0 }, { type: 1, status: 0 }
    ],

    houseNumber: null,//房源编号
    houseDetail: {},//新房详情
    formats: [],//户型数组
    //创建评论参数
    createCommentData: {
      content: "",
      images: [],
      houseNumber: "",
      parentId: "",
      grandId: "",
    },
    //评论的点击数据，评论成功后，直接强更，不去这个拉取列表
    commentData: {},
    commentType: "main",//main是代表一级评论，sub是代表二级带回复的评论
    //一级评论的index:
    oneLevelIndex: 0,
    currentSearchTitle: "公交",
    currentBottomIndex: 0,
    mapSearchList: [],




    showExpertPop: false,//咨询置业顾问弹窗
    bindUserId: "",//绑定关系的userId,
    isScanEnter: false,//是否是扫码进来的
    isShare: false,//是否分享进来的
    roleType: 1,//角色等级
    zhuChangeArr: [],
    videoArr: [],//房源视频arr;
    allTopImgArr: [],//房源所有图片arr
    houseTypeIndex: 0,
    scrollTopValue: 0,//到顶部距离
    bindHouse: 0,//是否是绑定房源进来的
    selectCompanyNumber: "",//选中的代理公司
    residentArr: [],//驻场arr
    cityName: "",
    sameHouseList: [
      { type: 1 }, { type: 1 }, { type: 1 }, { type: 1 }
    ],
    communityNumber: null,
    communityHouseList: [],//同小区房源





    detailId: null,
    onlineCustomer: {},
    mealList: [], // 套餐列表
    selectMealData: {},//选中的套餐
    showMealPop: false,
    isFriend: 0,
    btnType: 0,// 0:立即兑换 1:加入购物车
    detailType: 'normal',
    couponPrice: 0,//券后价
    ableCouponList: [],//可用优惠券列表
    maxCoupon: {}, //最大优惠券
    goodType: 'normal',//普通商品， seckill:秒杀商品
    replyInfo: {},//评价信息
    isShowSharePop: false,//是否显示分享弹窗
    isShowPosterPop: false,//是否弹出海报弹窗
    posterImg: "",//海报图片
    customActionStyle: {},
    posterInfo: {

    },
    posterData: {
      "width": "650rpx",
      "height": "950rpx",
      "background": "transparent",
      "views": [

      ]
    },
    posterViews: [
      //背景
      {
        "type": "image",
        "url": "https://images.jiabao19.com/common/whitebg.png",
        "css": {
          "width": "650rpx",
          "height": "950rpx",
          "top": "0rpx",
          "left": "0rpx",
          "rotate": "0",
          "borderRadius": "",
          "borderWidth": "",
          "shadow": "",
          "mode": ""
        }
      },
      // 头像
      {
        "type": "image",
        "url": "",
        "css": {
          "width": "80rpx",
          "height": "80rpx",
          "top": "50rpx",
          "left": "30rpx",
          "rotate": "0",
          "borderRadius": "40rpx",
          "borderWidth": "",
          "borderColor": "#000000",
          "shadow": "",
          "mode": "aspectFill"
        }

      },
      //昵称:
      {
        "type": "text",
        "text": "",
        "css": {
          top: "50rpx",
          left: "130rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "30rpx",
          "fontWeight": "bold",
          "color": "#333333",
        }
      },
      //标语:
      {
        "type": "text",
        "text": "嗨！给你推荐一个好物，快来看看吧！",
        "css": {
          top: "90rpx",
          left: "130rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "26rpx",
          "fontWeight": "normal",
          "color": "#b9b9b9",
        }
      },
      //封面
      {
        "type": "image",
        "url": "",
        "css": {
          "width": "590rpx",
          "height": "600rpx",
          "top": "160rpx",
          "left": "30rpx",
          "rotate": "0",
          "borderWidth": "",
          "borderColor": "#000000",
          "shadow": "",
          "borderRadius": "10rpx",
          "mode": "aspectFill"
        }

      },
      //价格单位:
      {
        "type": "text",
        "text": "",
        "css": {
          top: "700rpx",
          left: "30rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "28rpx",
          "color": "#ff0000",
        }
      },
      // 价格
      {
        "type": "text",
        "text": "",
        "css": {
          top: "680rpx",
          left: "120rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "45rpx",
          "fontWeight": "bold",
          "color": "#ff0000",
        }
      },
      //二维码
      {
        "type": "image",
        "url": "",
        "css": {
          "width": "120rpx",
          "height": "120rpx",
          "top": "780rpx",
          "right": "50rpx",
          "rotate": "0",
          "borderWidth": "",
          "borderColor": "#000000",
          "shadow": "",
          "mode": "aspectFill"
        }

      },
      //二维码提示:
      {
        "type": "text",
        "text": "长按查看商品",
        "css": {
          top: "905rpx",
          right: "30rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "26rpx",
          "fontWeight": "normal",
          "color": "#b9b9b9",
        }
      },
      //商品名称1
      {
        "type": "text",
        "text": "",
        "css": {
          // top: "780rpx",
          top: "815rpx",

          left: "30rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "30rpx",
          "fontWeight": "bold",
          "color": "#333333",
        }
      },
      //商品名称2
      {
        "type": "text",
        "text": "",
        "css": {
          // top: "820rpx",
          top: "850rpx",
          left: "30rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "30rpx",
          "fontWeight": "bold",
          "color": "#333333",
        }
      },
    ],
    userInfo: {
      nickname: "",
      avatar: "",
      promotionLevel: 0,//大于1就不显示佣金那种
    },
    isQueryUserInfo: false,//是否需要获取个人信息
    isCanTop: false,//是否可以滚动到顶部
    productQrCode: "",//商品分享二维码
    shareUserId: null,//分享id
    productSkuList: [],//可选规格。
    productSelectSku: {
      suk: "默认"
    },//当前已选规格
    videoCoverUrl: VIDEO_COVER,
    topBannerImgs: [],//纯图片banner
    bindArticle: { id: null },//绑定的知识内容
    productTags: [],//商品标签
    isScrollAction: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    console.log("JJLog:商品详情页参数是============：" + JSON.stringify(options));
    if (options.userId) {
      //通过复制短链进来的就需要在这里绑定关系
      wx.setStorageSync(BIND_USER_ID, options.userId);
    }
    //朋友圈进来参数是： {'houseNumber'：8，'isFriend':1,'userId':3};
    if (options.goodType == 'seckill') {
      this.setData({
        countTimestamp: app.globalData.countTimestamp,
        goodType: 'seckill'
      })
    }
    // 个人信息赋值
    if (app.globalData.userInfo && app.globalData.userInfo.nickname) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
    } else {
      this.setData({
        isQueryUserInfo: true,
      })
    }

    if (options.type) {
      this.setData({
        detailType: options.type
      })
    }

    let lanuchObj = wx.getLaunchOptionsSync();
    if (options.isFriend && options.isFriend == 1) {
      this.setData({
        isFriend: 1,
        houseNumber: options.houseNumber,
      })
      wx.setStorageSync(BIND_USER_ID, options.userId);
    }
    if (lanuchObj.scene == 1155) {
      this.setData({
        isFriend: 0,
        isShare: true,
      })
    }
    if (this.data.isFriend == 1) {
      return;
    }


    if (options.houseNumber) {
      this.setData({
        houseNumber: options.houseNumber,
        // communityNumber: options.communityNumber
      })
    }
    if (options.productId) {
      this.setData({
        houseNumber: options.productId,
      })
    }
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })



    //扫码进来的
    if (options.scene) {
      let scene = decodeURIComponent(options.scene)
      console.log("JJLog:扫码结果是==========:" + scene);
      let sceneArray = scene.split("=");
      let pStr = sceneArray[0];
      let bindStr = sceneArray[1]
      let pArr = pStr.split("&");
      let bindArr = bindStr.split("&");
      let houseNumber = pArr[1];
      let bindUserId = bindArr[1];
      console.log("JJLog:扫码进入的详情id:" + houseNumber);
      console.log("JJLog:扫码进入的bindId:" + bindUserId);
      wx.setStorageSync(BIND_USER_ID, bindUserId);


      this.setData({
        bindUserId: bindUserId,
        isShare: true,
        houseNumber: houseNumber
      })

      this.userWxLogin();

      return;
    }
    if (options.isShare) {
      this.setData({
        isScanEnter: false,
        isShare: true,
        bindUserId: options.userId,
      })
      wx.setStorageSync(BIND_USER_ID, options.userId);
      this.userWxLogin();

      return;
    }
    this.userWxLogin();

    if (!app.globalData.openId) {
      app.globalData.openId = wx.getStorageSync('openId');
    }

    // 绑定分享参数
    wx.onCopyUrl(() => {
      console.log("JJLog:绑定分享参数了============")
      return { query: `userId=${app.globalData.userId}&houseNumber=${this.data.houseNumber}` }
    })



  },
  onHide() {
    wx.offCopyUrl()
  },


  //用户登陆授权等:
  userWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      let data = res.data;
      if (res.code == 200) {
        app.globalData.nickName = data.nickName;
        app.globalData.avatar = data.avatar;
        app.globalData.phone = data.phone || "";
        app.globalData.isLogin = data.isLogin;
        app.globalData.openId = data.token;
        this.setData({
          shareUserId: data.uid,
          isLogin: data.isLogin
        })
        //绑定挂级关系:
        // if (this.data.bindUserId) {
        //   this.bindUserRelation();
        // }
        if (this.data.goodType == 'seckill') {
          //获取秒杀商品详情:
          this.querySeckillProductDetail();
        } else {
          this.queryStoreDetail();
        }

        this.queryProductReplyInfo();
        this.queryCartCount();
        if (this.data.isQueryUserInfo && app.globalData.isLogin) {
          this.queryUserInfo();
        }
      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);
    })
  },
  queryCartCount() {
    queryCartCount().then(res => {
      if (res.code == 200) {
        this.setData({
          cartNum: res.data.count,
        })
      }
    }).catch(err => {

    })
  },
  //获取个人信息api
  queryUserInfo() {
    queryUserInfo().then(res => {
      if (res.code == 200) {
        this.setData({
          userInfo: res.data,
        })

        app.globalData.userInfo = res.data
      }
    }).catch(err => {
      console.error("JJLog:queryUserInfo", err);
    })
  },
  openServiceAction() {
    wx.openCustomerServiceChat({
      extInfo: { url: SERVICE_URL },
      corpId: SERVICE_ID,
      success(res) { },
      fail(err) {
        console.log('调用失败:', err);
      }
    })
  },
  showSharePopActionNew() {
    this.setData({
      isShowSharePop: true,
    })
  },
  showSharePopAction() {
    if (this.data.isScrollAction) {
      this.setData({
        isScrollAction: false
      })
      return;
    }
    this.setData({
      isShowSharePop: true,
    })
  },
  showPosterPop() {
    //先生成海，再这个弹出弹窗
    if (!this.data.productQrCode) {
      wx.showToast({
        title: '海报暂时无法生成',
        icon: "none"
      })
      return;
    }

    if (this.data.posterImg) {
      this.setData({
        isShowSharePop: false,
        isShowPosterPop: true,
      })
      return;
    }
    wx.showLoading({
      title: '海报生成中...',
    })
    this.configPosterView();
  },
  closePosterPop() {
    this.setData({
      isShowPosterPop: false,
    })
  },
  //配置海报
  configPosterView() {
    //头像:
    let userAvatar = 'posterViews[' + 1 + '].url';
    //昵称:
    let userName = 'posterViews[' + 2 + '].text';
    //封面图:
    let houseCover = 'posterViews[' + 4 + '].url';
    //价格
    let goodPrice = 'posterViews[' + 6 + '].text';
    // 商品名称
    let goodName = 'posterViews[' + 9 + '].text';
    // 商品名称1
    let goodNameTwo = 'posterViews[' + 10 + '].text';
    // //二维码:
    let qrCode = 'posterViews[' + 7 + '].url';

    let storeName = this.data.productDetail.storeName;
    let storeNameOne = "";
    let storeNameTwo = "";
    if (storeName.length > 13) {
      storeNameOne = storeName.substring(0, 14);
      storeNameTwo = storeName.substring(14, storeName.length);
      if (storeNameTwo.length > 12) {
        storeNameTwo = storeNameTwo.substring(0, 12) + "..."
      }
    } else {
      storeNameOne = storeName;
      storeNameTwo = ""
    }


    this.setData({
      [userAvatar]: this.data.userInfo.avatar,
      [userName]: this.data.userInfo.nickname,
      [houseCover]: this.data.productDetail.image,
      // [goodPrice]: "￥" + this.data.productDetail.price,
      [goodPrice]: '',
      [goodName]: storeNameOne || "暂无",
      [goodNameTwo]: storeNameTwo || "",
      [qrCode]: this.data.productQrCode,
    })
    this.setData({
      'posterData.views': this.data.posterViews,
      posterInfo: this.data.posterData
    })
  },
  //生成海报成功:
  posterCreateSuccess(e) {
    wx.hideLoading();

    this.setData({
      isShowSharePop: false,
      isShowPosterPop: true,
      posterImg: e.detail.path,
    });

  },

  //生成海报失败:
  posterCreateError() {
    wx.hideLoading();
    wx.showToast({
      title: '生成海报失败',
      icon: "none"
    })
    // this.setData({
    //   showPosterImgView: false
    // })
  },
  //视频播放开始
  // videoPlayStart() {
  //   this.setData({
  //     swiperAutoplay: false,
  //   })
  // },
  // videoPauseAction() {
  //   this.setData({
  //     swiperAutoplay: true,
  //   })
  // },
  // videoEndAction() {
  //   setTimeout(() => {
  //     this.setData({
  //       swiperAutoplay: true,
  //     })
  //   })
  // },
  //保存海报到本地
  savePosterToLocal() {
    if (!this.data.posterImg) {
      wx.showToast({
        title: '暂无可保存海报图片',
        icon: "none"
      })
      return;
    }
    let that = this;
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              // 同意授权
              //保存到本地
              wx.saveImageToPhotosAlbum({
                filePath: this.data.posterImg,
                success(res) {
                  wx.showToast({
                    title: '保存海报成功',
                    icon: 'success',
                    duration: 2000
                  })

                },
                fail: (err) => {
                  console.log("JJLog:保存图片失败:" + JSON.stringify(err));
                  wx.showToast({
                    title: '保存海报失败',
                    icon: "none"
                  })
                }
              })
            },
            fail: (res) => {
              console.log(res);
              wx.showModal({
                title: '提示',
                content: '保存图片需要您同意访问您的相册',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting();
                  } else if (res.cancel) {
                    // console.log('用户点击取消')
                  }
                }
              })


            }
          })
        } else {
          // 已经授权了
          //保存到本地
          wx.saveImageToPhotosAlbum({
            filePath: this.data.posterImg,
            success(res) {
              wx.showToast({
                title: '保存海报成功',
                icon: 'success',
                duration: 2000
              })

            },
            fail: (err) => {
              console.log("JJLog:保存图片失败:" + JSON.stringify(err));
              wx.showToast({
                title: '保存海报失败',
                icon: "none"
              })
            }
          })
        }
      },
      fail: (res) => {
        console.log(res);
      }
    })
  },
  //获取商品评价信息
  queryProductReplyInfo() {
    queryProductReplyInfo(this.data.houseNumber).then(res => {
      console.log("JJLog:获取到的评价信息是：" + JSON.stringify(res))
      if (res.code == 200) {
        res.data.productId = this.data.houseNumber;
        this.setData({
          replyInfo: res.data
        })
      }
    }).catch(err => {
      console.error('queryProductReplyInfo', err);
    })
  },
  pushToReplyList() {
    wx.navigateTo({
      url: '/featurePackage/pages/commentList/commentList?productId=' + this.data.houseNumber + "&type=no",
    })
  },
  pushToQrCode() {
    // this.setData({
    //   isShowQrcodeEnter: false,
    // })
    wx.navigateTo({
      url: '/featurePackage/pages/companyWxService/companyWxService',
    })
  },
  //切换到购物车页面
  switchToCartPage() {
    wx.switchTab({
      url: '/pages/newList/newList',
    })
  },
  receviceCouponShow() {
    this.setData({
      showCouponPop: true,
    })
  },

  //绑定挂级关系:
  bindUserRelation() {
    let type = 1;
    if (this.data.isScanEnter) {
      type = 1;
    } else {
      type = 2;
    }
    bindUserRelation(type, this.data.bindUserId, this.data.houseNumber).then(res => {
      console.log("JJLog:绑定挂级关系:" + JSON.stringify(res));
      if (res.code == 200) {
        // this.queryNewHouseExpert();

      }
    }).catch(err => {
      console.error("JJLog:bindUserRelation:", err);
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
    this.setData({
      isLogin: app.globalData.isLogin
    })
    // this.setData({
    //   roleType: app.globalData.roleType || 1
    // })
  },



  //查询新商品详情:
  queryStoreDetail() {
    wx.showLoading();
    queryProductDetail(this.data.houseNumber, this.data.detailType).then(res => {
      console.log("JJLog:新商品详情是=====:" + JSON.stringify(res));
      this.setData({
        scrollRefreshStatus: false,
      })
      wx.hideLoading();
      if (res.code == 200) {
        let commission = res.data.maxCommission;
        if (commission && commission != '0.00') {
          commission = commission.split('.')[0]
        }
        res.data.productInfo.content = res.data.productInfo.content.replace(/style="[^"]*line-height: 1;[^"]*"/g, 'style="line-height: 0;"')
        console.log("JJLog:这个是：" + res.data.productInfo.content);
        this.setData({
          loadingStatus: true,
          bidProductData: res.data,
          storeInfo: res.data.storeInfo || "",
          productAttr: res.data.productAttr,
          productDetail: res.data.productInfo,
          productValue: res.data.productValue,
          showCommission: res.data.showCommission,
          maxCommission: commission,
          bindArticle: res.data.article || { id: '' }
        })
        // console.log("JJLog:实际的：" + JSON.stringify(this.data.productDetail));
        this.queryProductCoupon();
        this.queryShareQrCode()
        this.houseDataDeal(res.data.productInfo, res.data.productAttr, res.data.productValue);
      }
    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:queryProductDetail", err);
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
    })
  },
  querySeckillProductDetail() {
    wx.showLoading();
    querySeckillProductDetail(this.data.houseNumber).then(res => {
      console.log("JJLog:秒杀商品详情是=====:" + JSON.stringify(res));
      this.setData({
        scrollRefreshStatus: false,
      })
      wx.hideLoading();
      if (res.code == 200) {
        this.setData({
          loadingStatus: true,
          bidProductData: res.data,
          productAttr: res.data.productAttr,
          productDetail: res.data.storeSeckill,
          productValue: res.data.productValue,
          countTimestamp: res.data.storeSeckill.timeSwap
        })
        this.houseDataDeal(res.data.storeSeckill, res.data.productAttr, res.data.productValue);
        this.queryShareQrCode()
      }
    }).catch(err => {
      wx.hideLoading();
      console.error("JJLog:querySeckillProductDetail", err);
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
    })
  },

  //查询商品可以用的优惠券有哪些
  queryProductCoupon() {
    queryProductCoupon(this.data.houseNumber).then(res => {
      if (res.code == 200) {
        let arr = res.data.list || [];
        if (arr.length > 0) {
          let ableArr = []
          //先找出可用的优惠券 
          arr.forEach(i => {
            if ((parseInt(i.minPrice) < parseInt(this.data.productDetail.price)) || (parseInt(i.minPrice) == parseInt(this.data.productDetail.price))) {
              //最小使用金额小于当前价格:
              ableArr.push(i)
            }
          })

          if (ableArr.length < 1) {
            //证明没有可用优惠券
            this.setData({
              couponPrice: 0,
              ableCouponList: [],
              maxCoupon: {}
            })
            return;
          }
          //第二步：找出可用优惠券中最大的使用金额:
          let maxNum = parseInt(ableArr[0].money);
          let len = ableArr.length;
          let maxIndex = 0;
          for (let i = 1; i < len; i++) {
            if (parseInt(ableArr[i].money) > maxNum) {
              maxNum = ableArr[i].money;
              maxIndex = i;
            }
          }
          let maxCoupon = ableArr[maxIndex];

          this.setData({
            couponPrice: mathUtil.sub(this.data.productDetail.price, maxCoupon.money),
            ableCouponList: ableArr || [],
            maxCoupon: maxCoupon
          })
        }
      }
    }).catch(err => {
      console.error("JJLog:queryProductCoupon", err);
    })
  },

  //跳转到知识入口
  pushToKnoEnter() {
    if (this.data.bindArticle.id) {
      if (this.data.bindArticle.type == 0) {
        wx.navigateTo({
          url: '/pages/richPage/richPage?id=' + this.data.bindArticle.id,
        })
      } else {
        wx.navigateTo({
          url: '/pages/videoPlay/videoPlay?id=' + this.data.bindArticle.id,
        })
      }
    }
  },
  // 显示选择套餐弹窗:
  showSelectMealPop() {
    this.setData({
      showMealPop: true,
    })
  },
  //关闭选择套餐
  closeGoodsSelectPop() {
    this.setData({
      showMealPop: false
    })
  },
  // 选择套餐点击:
  selectMealAction(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      selectMealData: item,
      showMealPop: false,
    })

    if (this.data.btnType == 0) {
      //立即兑换
      this.pushToExchangeAction();
    } else {
      //加入购物车
      this.addShopToCartAction();
    }
  },
  closeCouponSelectPop() {
    this.setData({
      showCouponPop: false
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  // onPullDownRefresh: function () {

  //   //显示顶部刷新图标
  //   wx.showNavigationBarLoading();
  //   this.queryStoreDetail();
  //   console.log("JJLog:下拉刷新开始了===");
  //   //要刷新请求服务器的方法
  //   // this.selectCar();
  //   //隐藏导航栏加载框
  //   // wx.hideNavigationBarLoading();
  //   //停止下拉事件
  //   // wx.stopPullDownRefresh();
  // },

  //下拉刷新页面方法
  refreshPageMethod() {
    // wx.showLoading({
    //   title: '刷新中...',
    // })
    // setTimeout(() => {
    //   wx.hideLoading();
    //   wx.stopPullDownRefresh();
    // }, 2000);
  },

  //顶部swiper切换方法:
  topImgSwiperChange(e) {
    this.setData({
      currentSwiperIndex: e.detail.current
    })
  },




  //是否收藏操作
  collectChangeAction() {
    if (!this.loginJudge()) {
      return
    }
    if (!this.data.bidProductData.userCollect) {
      //未收藏:
      this.handlerAddCollect();
    } else {
      this.handlerCancelCollect();
    }
  },
  //加入收藏
  handlerAddCollect() {
    wx.showLoading();
    addCollect({
      category: "product",
      id: this.data.productDetail.id
    }).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        this.setData({
          'bidProductData.userCollect': true,
        })
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '收藏失败',
        icon: "none"
      })
    })
  },
  //取消收藏
  handlerCancelCollect() {
    wx.showLoading();
    cancelCollect(
      {
        category: "product",
        productId: this.data.productDetail.id
      }
    ).then(res => {
      wx.hideLoading()
      if (res.code == 200) {
        this.setData({
          'bidProductData.userCollect': false,
        })
      }
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err || '操作失败',
        icon: "none"
      })
    })
  },



  //楼盘动态图片预览
  previewDynImg(e) {
    let index = e.currentTarget.dataset.index;
    let type = e.currentTarget.dataset.type;
    let cIndex = e.currentTarget.dataset.cindex;
    let arr = [];
    if (type == "dyn") {
      arr = this.data.houseDynamicList;
    }
    let pic = arr[cIndex].pics[index].url;
    let pics = arr[cIndex].pics;
    let urls = [];
    pics.forEach((item) => {
      urls.push(item.url);
    })

    wx.previewImage({
      current: pic,
      urls: urls,
    })
  },



  loginJudge() {
    if (!app.globalData.isLogin) {
      // wx.showToast({
      //   title: '登录授权后才能操作',
      //   icon: "none"
      // })
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return false;
    } else {
      return true;
    }

  },

  addShopToCartActionNew() {
    if (!this.loginJudge()) {
      return
    }
    if (this.data.goodType == 'seckill') {
      wx.showToast({
        title: '秒杀商品暂不支持加入购物车',
        icon: "none"
      })
      return;
    }
    this.setData({
      showMealPop: true,
      btnType: 1,
    })
  },

  // 添加商品到购物车:
  addShopToCartAction() {


    let requestData = {
      cartNum: 1,
      productId: this.data.houseDetail.id,
      productItemId: this.data.selectMealData.id,
    }
    wx.showLoading();
    mallAddCartRequest(requestData).then(res => {
      wx.hideLoading();
      console.log("JJLog:添加购物车操作:" + JSON.stringify(res));
      if (res.code == 200) {
        wx.navigateTo({
          url: '/shopMallPackage/pages/shopCarList/shopCarList',
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: '添加购物车失败',
        icon: "none"
      })
      console.error("JJLog:mallAddCartRequest", err);
    })
  },




















  pushToCartList() {
    wx.navigateTo({
      url: '/shopMallPackage/pages/shopCarList/shopCarList',
    })
  },

  //详情数据处理:
  houseDataDeal(data, attr, productValue) {
    //1.图片，视频显示处理 
    //顶部轮播图处理: 只要这个视频 加上 封面 加上 效果图
    let tempImg = data.image;
    let imgArr = [];
    let sliderImgs = JSON.parse(data.sliderImage);
    let allImgs = [];
    let videos = [];
    sliderImgs.forEach(i => {
      let arr = i.split('.');
      let tailStr = arr[arr.length - 1];
      if (['mp4', 'wmv', 'avi', 'rmvb', 'mkv'].includes(tailStr)) {
        //就证明是视频：
        videos.push({
          type: 11,//视频，
          url: i,
          cover: i + this.data.videoCoverUrl
        })
      } else {
        allImgs.push({
          type: 1,
          url: i
        })
      }
    })

    if (allImgs && allImgs.length > 0) {
      imgArr = allImgs;
    } else {
      imgArr = [{
        type: 1,
        url: tempImg,
      }]
    }
    this.setData({
      topBannerImgs: imgArr
    })

    //有视频的情况，就将视频和图片数组结合到一起当作顶部banner，只是视频用video作为承载
    if (videos && videos.length > 0) {

      this.setData({
        topBanners: [...videos, ...imgArr],
        swiperAutoplay: false,//有视频就不让自动播放了
      })
    } else {
      this.setData({
        topBanners: imgArr
      })
    }

    if (data.tags && data.tags.length > 0) {
      this.setData({
        productTags: data.tags,
      })
    }







    //图片视频处理 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    //商品规格处理：
    let productSku = "";
    let productSkuArr = [];
    attr.forEach((i) => {
      let attrValues = i.attrValues;
      let attrValueArr = attrValues.split(',');
      productSkuArr.push(attrValueArr[0]);
    })
    productSku = productSkuArr.join(",");
    this.setData({
      productSku: productSku,
    })

    let pValueKeys = Object.keys(productValue);
    let pSkuList = [];
    pValueKeys.forEach(i => {

      if (i == productSku) {
        this.setData({
          productSelectSku: productValue[i],
        })
      }
      pSkuList.push(productValue[i]);
    })
    this.setData({
      productSkuList: pSkuList
    })
    console.log("JJLog:规整的数据是：" + JSON.stringify(this.data.productSkuList))
    console.log("JJLog:规整的数据是====：" + JSON.stringify(this.data.productSelectSku))


    // let tags = [];
    // if (data.keyword) {
    //   tags.push(data.keyword)
    // }
    // this.setData({
    //   'houseDetail.tags': tags
    // })





  },

  //商品添加购物车成功
  addCartSuccess() {
    this.queryCartCount();
    this.setData({
      showMealPop: false,
    })
  },

  //获取房源的评论列表:
  queryNewHouseComment() {
    queryNewHouseComment(this.data.houseNumber).then(res => {
      console.log("JJLog:楼盘评论列表:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          commentList: res.data
        })
      }
    }).catch(err => {
      console.error("JJLog:楼盘评论列表失败:" + JSON.stringify(err));
    })
  },
  pushToExchangeActionNew() {
    if (!this.loginJudge()) {
      return
    }
    //将最大优惠券默认领取一下。
    if (JSON.stringify(this.data.maxCoupon) != "{}") {
      if (!this.data.maxCoupon.isUse) {
        //默认帮忙领取了：
        receiveCoupon({ couponId: this.data.maxCoupon.id }).then(res => {
          if (res.code == 200) { }
        }).catch(err => {
          console.error("JJLog:receiveCoupon", err)
        })
      }
    }
    this.setData({
      btnType: 0,
    })
    this.showSelectMealPop();
  },















  clickCenterPopupOverlay() {
    this.setData({
      showSharePop: false,
      showEmptySharePop: false,
      showRulePopup: false,
      showMealPop: false,
      isShowSharePop: false,
    })
  },



  //底部按钮微信分享:
  bottomWxShare() {
    if (!app.globalData.houseQrCode) {
      wx.showToast({
        title: '暂时无法分享房源',
        icon: "none"
      })
      return;
    }
    let data = this.data.houseDetail;
    let obj = {
      houseName: data.name,
      houseNumber: data.houseNumber,
      coverPic: data.coverPic,
      areaName: data.areaName,
      unitPrice: data.unitPrice,
      totalPrice: data.totalPrice,
      area: data.formatArea,
      qrCode: app.globalData.houseQrCode,
    }
    app.globalData.posterHouse = obj;
    wx.navigateTo({
      url: '/newHousePackage/pages/housePoster/housePoster?type=house',
    })
  },

  //咨询专家:
  askExpertAction() {

    if (this.data.expertArr && this.data.expertArr.length > 0) {
      this.setData({
        showExpertPop: true
      })
    } else {
      wx.showToast({
        title: '暂无咨询专家',
        icon: "none"
      })
    }


  },
  exportPopHidden() {
    this.setData({
      showExpertPop: false
    })
  },
  //置业顾问拨打电话
  exportPhoneClick(e) {
    console.log("JJLog:电话:" + JSON.stringify(e));
    let item = e.detail.item;
    this.commonMakePhone(item);
  },
  //置业顾问聊天
  exportMsgClick(e) {
    console.log("JJLog:聊天:" + JSON.stringify(e));
    let item = e.detail.item;
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      this.setData({
        showExpertPop: false
      })
      return;
    }
    this.commonExpertChatAction(item);
  },

  //跳转到评论列表去
  pushToMoreComment() {
    let houseNumber = this.data.houseDetail.houseNumber;
    wx.navigateTo({
      url: '/newHousePackage/pages/houseAllComment/houseAllComment?houseNumber=' + houseNumber,
    })
  },
  //跳转到更多楼盘动态去:
  pushToMoreHouseDyn() {
    let houseNumber = this.data.houseDetail.houseNumber;
    wx.navigateTo({
      url: '/newHousePackage/pages/houseAllDyn/houseAllDyn?houseNumber=' + houseNumber + "&isManager=" + 0,
    })
  },
  //复制微信号:
  copyWxChatAction(e) {
    let text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '微信号复制成功',
              icon: "none"
            })
          },
          fail: function (err) {
            wx.showToast({
              title: '复制失败',
              icon: "none"
            })
          }
        })
      }
    })
  },
  //咨询置业顾问聊天;
  expertChatAction(e) {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    let item = e.currentTarget.dataset.item;
    this.commonExpertChatAction(item);

  },
  //公共的咨询置业顾问
  commonExpertChatAction(item) {
    this.setData({
      showExpertPop: false,
    })
    let name = "";
    if (item.realName) {
      name = item.realName;
    } else if (item.name) {
      name = item.name;
    }
    else {
      name = item.nickName
    }
    let chatData = {
      name: name,
      avatar: item.avatar,
      chatUserId: item.openId,
      conversationType: "C2C",
      // houseNumber: this.data.houseDetail.houseNumber,
      // houseName: this.data.houseDetail.name,
      // houseCover: this.data.houseDetail.coverPic,
      // housePrice: this.data.houseDetail.totalPrice,
      // houseDesc: this.data.houseDetail.areaName + " | " + "建面" + this.data.houseDetail.formatArea + "㎡",
      // expertId: item.id,
      // expertPhone: item.phone || "",
      // expertWeChat: item.wxChat || "",
    }
    app.globalData.chatData = chatData;
    wx.navigateTo({
      url: '/firstPackage/pages/msgModule/chatRoom/chatRoom',
    })
  },
  //公共的打电话
  commonMakePhone(item) {
    if (item.phone) {
      wx.makePhoneCall({
        phoneNumber: item.phone,
        fail: err => {

        }
      })
      this.setData({
        showExpertPop: false
      })
      // this.expertPhoneActionA(item.id);
    } else {
      wx.showToast({
        title: '暂无电话',
        icon: "none"
      })
      this.setData({
        showExpertPop: false
      })
    }
  },
  expertPhoneAction(e) {
    let item = e.currentTarget.dataset.item;
    this.commonMakePhone(item);
  },

  bottomChatAction() {
    if (this.data.expertArr && this.data.expertArr.length > 0) {
      this.setData({
        showExpertPop: true
      })
    } else {
      wx.showToast({
        title: '暂无客服',
        icon: "none"
      })
    }


  },
  //底部关注或者取关房源:
  bottomCollectAction() {
    let collect = this.data.houseDetail.isCollection;
    this.houseAttentionAction(collect);
  },
  //房源的关注或者取关
  houseAttentionAction(collect) {
    let data = {
      collectType: 1,
      number: this.data.houseDetail.houseNumber
    }
    wx.showLoading();
    attentionAction(data).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        this.setData({
          'houseDetail.isCollection': !collect
        })
        wx.showToast({
          title: collect ? "取关成功" : "关注成功",
          icon: "none"
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "操作失败",
        icon: "none"
      })
      console.error("JJLog:attentionAction", err);
    })
  },



  //跳转到注册页面
  pushToLogin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },















  //scrollView下拉刷新
  refreshDownData() {
    console.log("JJLog:刷新到这里来了=====");
    this.setData({
      scrollRefreshStatus: true
    })


    // this.queryNewHouseOtherDetail();
    // this.queryNewHouseExpert();
    // this.queryNewHouseComment();
    if (this.data.goodType == 'seckill') {
      //获取秒杀商品详情:
      this.querySeckillProductDetail();
      return;
    }
    this.queryStoreDetail();
  },
  queryShareQrCode() {
    let data = {
      params: {
        u: this.data.shareUserId,//个人userId,
        h: this.data.houseNumber,//产品编号
      },
      page: "shopMallPackage/pages/newStoreDetail/newStoreDetail"
    }
    queryShareQrCode(data).then(res => {
      console.log("JJLog:获取到的商品二维码是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          productQrCode: res.data.code || ""
        })
      }

    }).catch(err => {

    })
  },


  //回到首页
  backHomeAction() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  onScroll(event) {
    if (!this.data.isScrollAction) {
      this.setData({
        isScrollAction: true,
      })
    }
    wx.createSelectorQuery()
      .select('#scroller')
      .boundingClientRect((res) => {
        this.setData({
          scrollTop: event.detail.scrollTop,
          offsetTop: res.top,
        });
      })
      .exec();
    // 判断是否显示回到顶部按钮
    if (event.detail.scrollTop > 300) {
      this.setData({
        isCanTop: true
      });
    } else {
      this.setData({
        isCanTop: false
      });
    }
  },
  //回到顶部方法
  scrollToTopAction() {
    this.setData({
      scrollTopValue: 0,
      // isScrollAction: false,
    })
  },
  //滚动点击:
  horizontalTapAction(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      horizontalSwiperIndex: index
    })
  },
  //底部预约楼盘
  bottomBookingAction() {
    let houseName = this.data.houseDetail.name;
    let houseNumber = this.data.houseDetail.houseNumber;
    wx.navigateTo({
      url: '/formPackage/pages/appointment/myAppointment/myAppointment?houseName=' + houseName + "&houseNumber=" + houseNumber,
    })
  },
  createNewShareTeamAction() {
    this.setData({
      showSharePop: false,
      showEmptySharePop: true
    })
  },
  keyBoardHeightChange(e) {
    let height = e.detail.height;
    console.log("JJLog:高度变化时:" + height)
    this.setData({
      keyBoardHeight: height,
    })
  },
  // swiperItemClick(e) {
  //   let url = e.currentTarget.dataset.url;
  //   let arr = e.currentTarget.dataset.arr;
  //   let urls = [];
  //   arr.forEach((item) => {
  //     urls.push(item.url)
  //   })
  //   wx.previewImage({
  //     current: url,
  //     urls: urls,
  //   })
  // },

  //预览视频:
  previewImgOrVideo() {
    //视频
    let videoUrl = this.data.videoArr[0].url;
    app.globalData.videoUrl = videoUrl;
    wx.navigateTo({
      url: '/pages/videoPlay/videoPlay',
    })
  },
  //预览图片:
  previewImgAction(e) {
    let url = e.currentTarget.dataset.url;
    let arr = e.currentTarget.dataset.arr;
    let urls = [];
    arr.forEach((item) => {
      urls.push(item.url);
    })
    wx.previewImage({
      current: url,
      urls: urls,
    })
  },
  // 户型顶部切换:
  houseTypeChangeAction(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      houseTypeIndex: index
    })
    if (index == 0) {
      this.setData({
        topBanners: this.data.videoArr,
        currentSwiperIndex: 0
      })
    } else {
      this.setData({
        topBanners: this.data.allTopImgArr,
        currentSwiperIndex: 0
      })
      // console.log("JJLog:topBanners:" + JSON.stringify(this.data.topBanners));
    }
  },
  //跳转到更多专家列表:
  pushToMoreExpertListAction() {
    let houseNumber = this.data.houseDetail.houseNumber;
    if (this.data.expertArr && this.data.expertArr.length == 3) {
      wx.navigateTo({
        url: '/newHousePackage/pages/newHouseExpertList/newHouseExpertList?houseNumber=' + houseNumber,
      })
    }

  },

  //滑动监听
  bindscrollAction(e) {
    // console.log("JJLog:滚动监听:" + JSON.stringify(e));
    let scrollTopValue = e.detail.scrollTop;
    this.setData({
      scrollTopValue: scrollTopValue,
    })
  },












  //跳转到分享海报页面
  pushToSharePage() {
    // if (!app.globalData.houseQrCode) {
    //   wx.showToast({
    //     title: '暂时无法分享房源',
    //     icon: "none"
    //   })
    //   return;
    // }
    let data = this.data.houseDetail;
    let obj = {
      houseName: data.titleDesc,
      houseNumber: data.houseNumber,
      coverPic: data.coverPic,
      areaName: data.areaName || "暂无",
      totalPrice: data.totalPrice,
      area: data.area,
      qrCode: app.globalData.houseQrCode,
    }
    app.globalData.posterHouse = obj;
    wx.navigateTo({
      url: '/newHousePackage/pages/housePoster/housePoster?type=secondHouse',
    })
  },

  backHomeAction() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let path = "";
    path = "/shopMallPackage/pages/newStoreDetail/newStoreDetail?isShare=1" + "&userId=" + app.globalData.userId + "&houseNumber=" + this.data.houseNumber

    return {
      title: this.data.productDetail.storeName || app.globalData.commonShareTitle,
      path: path
    }
  },
  onShareTimeline: function () {
    return {
      title: this.data.productDetail.storeName || app.globalData.commonShareTitle,
      query: "isFriend=1" + "&userId=" + app.globalData.userId + "&houseNumber=" + this.data.houseNumber,
      imageUrl: this.data.houseDetail.image
    }


  },
})